import requests
import warnings
import time
from datetime import datetime
from utils import close_qemu, read_config


def try_web_access(port):
    url = "https://127.0.0.1:{}/UI/Rest/Login".format(port)
    retcode = -1
    session = requests.Session()
    session.trust_env = False
    try:
        with warnings.catch_warnings():
            warnings.simplefilter(
                "ignore", category=requests.packages.urllib3.exceptions.InsecureRequestWarning)
            response = session.get(url, timeout=10, proxies={}, verify=False)
            retcode = response.status_code
    except requests.exceptions.RequestException as e:
        pass
    return retcode == 200

def execute():
    status = False
    config = read_config()
    web_port = config['mapports']['https']
    print(web_port)
    print("正在连接bmc...")
    start_time = datetime.now()
    while not status:
        end_time = datetime.now()
        if (end_time - start_time).total_seconds() >= 600:
            print("❌ 连接bmc超时(10分钟)...")
            close_qemu()
            exit(1)
        status = try_web_access(web_port)
        # 短暂等待，避免CPU过载
        time.sleep(0.1)
    print("✅ 连接bmc成功!")


if __name__ == "__main__":
    execute()
